
//新版基础函数
var f = {
    init:function() {
        log("程序初始化成功")
    },
    //post
    post : function(url,data){
        var res = http.post(url, data);
        var data = res.body.string();
        if(data){
            // log(data);
            return data;
        }
    },
    //get
    get : function(url){
        var res = http.get(url);
        var data = res.body.string();
        if(data){
            return data;
        }
    },
    //读取本地数据
    getLocal:function ( name, key) {
        const storage = storages.create(name);  //创建storage对象
        if (storage.contains(key)) {
            return storage.get(key);
        };
        //默认返回undefined
    },
    //基础函数
    active:function(pkg,n){
        if(!n){n=5}
        if(  currentPackage() == pkg ){
            log("应用在前端");
            return true;
        }else{
            log("启动一次应用");
            app.launch(pkg);
            sleep(1000)
            f.ms({"textMatches":"允许|始终允许"},true)
            sleep(1000*n)
        }
    },
    //准备点击
    click:function (x,y,sleeptime,name){
        if ( ! sleeptime ){sleeptime = 1}
        if ( name ){
            log('准备点击->'+name,"x:",x,"y:",y);
        }else{
            log('准备点击坐标->', "x:",x,"y:",y);
        }
        if( x > 0  && y > 0  ){
            threads.start(function(){
                //在新线程执行的代码
                click(x,y);
            });
            // click(x,y);
            sleep(sleeptime*1000);
            return true
        }else{
            log('坐标错误');
        }
    },
    //点击obj
    clickObj:function (obj,sleeptime,name){
        if ( ! sleeptime ){ sleeptime == 1 } 
        log(  name ? ("准备点击对象->" + name) : "点击未命名对象" )
        x = obj.bounds().centerX()
        y = obj.bounds().centerY()
        return f.click(x,y,sleeptime,name)
    },
    //穿透点击
    clickTrue:function(obj,sleeptime,name,lun){
        sleeptime ? sleeptime : 1
        let result = false;
        lun ? lun : 3
        for (let i=0;i<lun;i++){
            if (  obj && obj.clickable() ){
                obj.click();
                log(  name ? ("准备穿透点击对象->" + name) : "准备穿透点击未命名对象" )
                result = true
                break
            }
            obj = obj.parent()
        }
        if ( result ) { sleep(sleeptime * 1000) }
        return result
    },
    //正则点击
    ms:function (obj,clicks,sleeptimes,name,findtime,lun){
        if (!sleeptimes) { sleeptimes = 1}
        if (!findtime) { findtime = 200}
        if (!lun) { lun = 3}

        var txt = '';
        for(let key in obj){
            if ( key.search("Matches") > 0 ){
                eval("var matches = /" + obj[key] + "/")
                txt = txt + key+'('+matches+').'
            }else if( key ==  'boundsInside' ){
                txt = txt + key+'('+obj[key]+').'
            }else{
                txt = txt + key+'("'+obj[key]+'").'
            }
        }
        var txt = "let objs = "+txt+"findOne("+findtime+");"
        log(txt)
        eval(txt)
        if ( objs ) {
            log( '找到==>' + objs.text() || objs.desc() || objs.id() || objs.className() )
            if ( clicks ){
                name = obj['textMatches'] || obj['descMatches'] || obj['idMatches'] || obj['text'] || obj['desc'] || obj['id']
                if (lun < 1 || !f.clickTrue( objs,sleeptimes,name,lun )){
                    log('准备坐标点击')
                    return f.clickObj( objs,sleeptimes,name );
                }
            }
            return true;
        }
    },
    rd:function (min,max){
        if (min<=max){
            return random(min,max)
        }else{
            return random(max,min)
        }
    },
    moveTo:function (percentX, percentY, percentX1, percentY1, times) {
        // 获取设备的宽度和高度
        const width = device.width;
        const height = device.height;

        // 将百分比转换为实际坐标
        const x = Math.round(width * percentX);
        const y = Math.round(height * percentY);
        const x1 = Math.round(width * percentX1);
        const y1 = Math.round(height * percentY1);

        // 执行滑动操作
        swipe(x, y, x1, y1, times);
        sleep(1000);
    }
}
f.init()

var width = 720;
var height = 1440;
var width = device.width;
var height = device.height;
var phoneMode = device.brand;

log([currentPackage(),currentActivity(),width,height]);

// 新增一个 post 方法，请求头为 json 格式，只需要传入 data 参数
f.postJson = function(url, data) {
    url = url || 'https://api.wenfree.cn/?s=App.Autojs_Tiktok.Spiders_video'
    var headers = {
        "Content-Type": "application/json"
    };
    log(url,JSON.stringify(data))
    var res = http.postJson(url, data, headers);
    var data = res.body.string();
    if(data){
        log(data);
        return data;
    }
};



var appInfo = {
    search_word: '',
    shop: '',
    categories: '',
    name: '',
    price: '',
    price_old: '',
    author: '',
    rate: '',
    sold: '',
    mintitle: '',
    alltitle: '',
    rank: '',
    link: '',
    fav: '',
    tag: '',
}
var storage = storages.create("tiktok");
var look = []
look = storage.get("look") || [];
// storage.remove("look");
log(look)


f.active("com.zhiliaoapp.musically", 2)


//批查打印app参数
function printAll(ways) {
    if (!ways) {
        ways = 'className'
    }
    if (ways = 'className') {
        var all_Info = classNameMatches(/.*/).find();
    } else
        if (ways == 'text') {
            var all_Info = textMatches(/.*/).find();
        } else
            if (ways == 'id') {
                var all_Info = idMatches(/.*/).find();
            } else {
                eval('var all_Info = ' + ways + '.find();')
            }

    if (all_Info) {
        for (var i = 0; i < all_Info.length; i++) {
            var d = all_Info[i];
            log(i, d.id(), d.text(), "desc:" + d.desc(), '"className":"' + d.className() + '"',
                "clickable->" + d.clickable(), 'selected->' + selected(), "depth->" + d.depth(),
                d.bounds().centerX(), d.bounds().centerY())
        }
    } else {
        log('没有找到任何相关的节点')
    }
}


printAll()

function postff(){
    let url = "http://1.15.122.129:5000/api/v1/video_info/add"
  
    let postData = {
        "creator_id": appInfo.name_id,
        "product_name": appInfo.v_title,
        "has_pillow": appInfo.target,
        "video_link": appInfo.link,
        "video_like": appInfo.likes,
        "video_share": appInfo.share,
        "video_comments": appInfo.commnet,
        "video_favorite": appInfo.fav,
        "video_view": appInfo.view,
        "crawl_time": new Date()
    }

    f.postJson(url, postData)
}

function postffcommnet(comments){
    let url = "http://1.15.122.129:5000/api/v1/video_comments/add"
  
    let postData = {
        "video_name": appInfo.v_title,
        "comments": comments,
        "time": new Date()
    }

    f.postJson(url, postData)
}



function get_nickname(){
    let r = f.get('https://api.wenfree.cn/Autojs_TiktokRed/Red')
    r = JSON.parse(r)
    if( r.data ){
        return r.data
    }
}

function save_vedio(data){
    let r = f.postJson('https://api.wenfree.cn/Autojs_TiktokRed/Vedio', data)
    r = JSON.parse(r)
    if( r.data ){
        return r.data
    }
}

function vedioPage(){
    if( f.ms({'id':"com.zhiliaoapp.musically:id/long_press_layout"})){
        log("在视频详情页面",'-----------------', vedioList)
        vedioList = vedioList + 1


        appInfo.target = 'NO'
        if( f.ms({textMatches:'.*Pillow.*|.*pillow.*'}) ){
            log("是带标记的视频")
            appInfo.target = 'YES'
            try {
                appInfo.shoptitle = id('ais').findOne(200).text()
            } catch (error) {
                log("取标题出错", error)
            }
            
        }

        // 处理标题
        var titles = id("com.zhiliaoapp.musically:id/title").find()
        if(titles){
            log("titles", titles.length)
            for (let index = 0; index < titles.length; index++) {
                let element = titles[index];
                log('titles', index, element.bounds().centerX(), element.bounds().centerY(), element.text())
                if (element.bounds().centerX() > 0 && element.bounds().centerX() < device.width && element.bounds().centerY() > 0 && element.bounds().centerY() < device.height) {
                    appInfo.title = element.text()
                    break
                }
            }
        }

        // 处理视频描述
        var v_titletitles = id("com.zhiliaoapp.musically:id/desc").find()
        if(v_titletitles){
            log("v_titletitles", v_titletitles.length)
            for (let index = 0; index < v_titletitles.length; index++) {
                let element = v_titletitles[index];
                log('v_titletitles', index, element.bounds().centerX(), element.bounds().centerY(), element.text())
                if (element.bounds().centerX() > 0 && element.bounds().centerX() < device.width && element.bounds().centerY() > 0 && element.bounds().centerY() < device.height) {
                    appInfo.v_title = element.text()
                    break
                }
            }
        }

        // 处理收藏数
        var fs1 = id("com.zhiliaoapp.musically:id/fs1").find()
        if(fs1){
            log("fs1", fs1.length)
            for (let index = 0; index < fs1.length; index++) {
                let element = fs1[index];
                log('fs1', index, element.bounds().centerX(), element.bounds().centerY(), element.text())
                if (element.bounds().centerX() > 0 && element.bounds().centerX() < device.width && element.bounds().centerY() > 0 && element.bounds().centerY() < device.height) {
                    // 只保留数字
                    appInfo.fav = element.text()
                    break
                }
            }
        }

        // 处理点赞数
        var likes = descMatches(".* likes").find()
        if(likes){
            log("likes", likes.length)
            for (let index = 0; index < likes.length; index++) {
                let element = likes[index];
                log('likes', index, element.bounds().centerX(), element.bounds().centerY(), element.desc())
                if (element.bounds().centerX() > 0 && element.bounds().centerX() < device.width && element.bounds().centerY() > 0 && element.bounds().centerY() < device.height) {
                    appInfo.likes = element.desc()
                    break
                }
            }
        }

        // 处理评论数
        var comments = descMatches(".* comments").find()
        if(comments){
            log("comments", comments.length)
            for (let index = 0; index < comments.length; index++) {
                let element = comments[index];
                log('comments', index, element.bounds().centerX(), element.bounds().centerY(), element.desc())
                if (element.bounds().centerX() > 0 && element.bounds().centerX() < device.width && element.bounds().centerY() > 0 && element.bounds().centerY() < device.height) {
                    appInfo.commnet = element.desc()
                    break
                }
            }
        }

        // 处理分享数
        var shares = descMatches(".* shares").find()
        if(shares){
            log("shares", shares.length)
            for (let index = 0; index < shares.length; index++) {
                let element = shares[index];
                log('shares', index, element.bounds().centerX(), element.bounds().centerY(), element.desc())
                if (element.bounds().centerX() > 0 && element.bounds().centerX() < device.width && element.bounds().centerY() > 0 && element.bounds().centerY() < device.height) {
                    appInfo.share = element.desc()
                    break
                }
            }
        }


        // if( f.ms({"descMatches":'Share.*'}, true, 3) ){
        //     f.ms({"text":'Copy link'}, true, 3 )
        //     f.active("org.fd.ffdd.v7", 3)
        //     var link = getClip()
        //     if (link){
        //         log('获取到链接', link)
        //         appInfo['link'] = link
        //     }
        //     f.active("com.zhiliaoapp.musically", 3)
        // }

        log(appInfo)
        var postData = {
            name: appInfo.nikcname,
            name_id: appInfo.name_id,
            target: appInfo.target,
            link: appInfo.link,
            title: appInfo.title,
            v_title: appInfo.v_title,
            view: appInfo.view,
            likes: appInfo.likes,
            commnet: appInfo.commnet,
            fav: appInfo.fav,
            orders: appInfo.orders,
            Pinned: appInfo.Pinned,
        }
        save_vedio(postData)
        postff()

        var comments = descMatches(".* comments").find()
        if(comments){
            log("comments", comments.length)
            for (let index = 0; index < comments.length; index++) {
                let element = comments[index];
                log('comments', index, element.bounds().centerX(), element.bounds().centerY(), element.desc())
                if (element.bounds().centerX() > 0 && element.bounds().centerX() < device.width && element.bounds().centerY() > 0 && element.bounds().centerY() < device.height) {
                    // 只保留数字部分，如果大于0才展开评论
                    var commentText = element.desc();
                    var commentNum = 0;
                    // 直接用 replace 去除非数字字符
                    var numStr = commentText.replace(/[^\d]/g, '');
                    if (numStr) {
                        commentNum = parseInt(numStr, 10);
                    }
                    log("提取到评论数：", commentNum);
                    if (commentNum <= 0) {
                        log("评论数为0，不展开评论");
                        break;
                    }
                    f.clickObj(element.parent(), 5, `展开评论${element.parent().bounds().centerX()} , ${element.parent().bounds().centerY()}`)
                    if( f.ms({"id":"android:id/text1", "textMatches":"Reviews.*"}, true, 10)){
                        for (let index = 0; index < 5; index++) {
                            var commnets = className("com.bytedance.ies.xelement.text.text.LynxTextUI").find()
                            if(commnets){
                                for (let index = 0; index < commnets.length; index++) {
                                    let e = commnets[index];
                                    log("长评论", e.text())
                                    postffcommnet(e.text())
                                }
                            }
                            f.moveTo(0.5,0.8,0.5,0.7, 2000)
                        }
                        back()
                    }
                    break
                }
            }
        }
    }
}


function main(){
    if( f.ms({"text":"verify captcha"}) ){
        
        return "captcha"
    }

    log('准备查主页')
    if( f.ms({"text":'Home'}) &&  f.ms({"text": 'Profile'}) ){
        log("在首页，去搜索页")
        f.ms({ "desc": 'Search', 'id': 'com.zhiliaoapp.musically:id/hha'}, true, 4)
    }
    
    log('准备查搜索页面')
    if( f.ms({"text":'You may like'}) &&  f.ms({"text": 'Refresh'}) ){
        log('搜索准备输入界面')
        setText(0, appInfo.nikcname)
        sleep(2000)
        var array = text("Search").find()
        if(array){
            for (let index = 0; index < array.length; index++) {
                let element = array[index];
                log(element.text(), element.bounds().centerX(), element.bounds().centerY())
                f.click(element.bounds().centerX(), element.bounds().centerY(), 6, '搜索')
                this.search = true
                vedioList = 0
            }
        }
    }
    
    log('准备查搜索结果页面')
    if( this.search && f.ms({"text": appInfo.nikcname }) && f.ms({ "descMatches" : "Video.*"+appInfo.nikcname+".*"})  ){
        log("搜索到了用户")
        f.ms({ "id": "com.zhiliaoapp.musically:id/v23" }, true, 5)
    }

    // this.search = true
    
    log('准备查搜是否在主页')
    // if( this.search && f.ms({ "id":'com.zhiliaoapp.musically:id/o66', "textMatches": '@'+appInfo.nikcname })){
    if( this.search && f.ms({ "id":'com.zhiliaoapp.musically:id/o66' })){
        log("确定的用户主页")

        var Pinneds = text("Pinned").find();
        if(Pinneds){
            log('有几个置顶', Pinneds.length)
        }
    

        var vedios = id("com.zhiliaoapp.musically:id/umk").find()
        if( vedios ){
            log("有几个视频", vedios.length, 'vedioList', vedioList)

            let element = vedios[vedioList]
            log('视频数据', element.text(), element.bounds().centerX(), element.bounds().centerY())
            appInfo.view = element.text()
            appInfo.orders = vedioList
            appInfo.Pinned = 0
            if( element.bounds().centerX() > 0 && element.bounds().centerX() < device.width && element.bounds().centerY() > 0 && element.bounds().centerY() < device.height ) {
                f.clickObj(element, 3, 'view'+element.text() )
                if(Pinneds){
                    if( vedioList < Pinneds.length ){
                        appInfo.Pinned = 1
                    }
                }
                sleep(5000)
                vedioPage()
                back()
                sleep(3000)
            }
            if( vedioList > 5 ){
                this.search = false
                this.next = true
            }else{
                f.moveTo(0.5,0.8,0.5,0.65, 2000)
            }
        }
    }else{
        log("突然找不到了？", 'search', this.search)
        // printAll()
        sleep(3000)
    }

    
}

var used_price = []
var appInfo = {}
var vedioList = 0

this.next = true
this.search = false

while ( 1 ){
    
    if( this.next ){
        // appInfo.nikcname = 'a_lewis913'
        var info = get_nickname() 
        if( info ){
            log(info)
            appInfo.nikcname = info.name
            appInfo.name_id = info.id
            log( appInfo )
        }
        this.next = false
    }
    try {
        let lunr = main()
        if( lunr == 'captcha' ){
            log("等待滑验证")
        }else{
            this.backs =  this.backs || 0
            this.backs++
            if( this.backs%6 == 0 ){
                back()
                sleep(3000)
            }
        }
    } catch (error) {
        
    }
    
    sleep(2000)
}



